package com.icebergteam.warfacewidget.rank.data;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.WidgetProvider;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.Parser;
import com.icebergteam.warfacewidget.core.connection.NetworkManager;
import com.icebergteam.warfacewidget.data.sql.NewsTable;
import android.content.ContentValues;
import android.database.SQLException;

public class Top100ClansParser extends Parser  {
	final public static String className = Top100ClansParser.class.getCanonicalName();
	
	public Top100ClansParser(boolean restoreKey) {
		super(restoreKey);
		
	}
	
	public Top100ClansParser() {
		super();
	}
	@Override
	public int saveData(String url) throws Exception {
		try {
			if (this.isRestoreKey() && AppManager.getDatabase().getRankTable().getCountCurrentUrl()>0){
				LogManager.LogV(Top100ClansParser.className, LogManager.getExecuteMethodName(),
						"generate restore");
				throw new Exception(WidgetProvider.RESTORE_ACTION); 
			}
			LogManager.LogVA(Top100ClansParser.className, url);
				
			this.doc = Jsoup.parse(NetworkManager.getResponseInputStream(url), "UTF-8", "");
			
			ContentValues dataToInsert = new ContentValues();    
			dataToInsert.put(NewsTable.FIELD_URL, url);
			dataToInsert.put(NewsTable.FIELD_HTML, this.doc.toString());
			dataToInsert.put(NewsTable.FIELD_PUBDATE, new Date().getTime());
			
						
			AppManager.getDatabase().getRankTable().updateOrInsert(dataToInsert);

			this.stateRequest = Parser.REQUEST_COMPLETED;
			LogManager.LogV(Top100ClansParser.className,  LogManager.getExecuteMethodName(), url);

		} catch (SocketTimeoutException e) {
			LogManager.LogE(Top100ClansParser.className,  LogManager.getExecuteMethodName(), "timeout");
			e.printStackTrace();
			restore(Parser.REQUEST_FAILED | Parser.LIST_RESTORED,
										Parser.REQUEST_FAILED | Parser.LIST_RESTORED);
		} catch (IOException e) {
			LogManager.LogE(Top100ClansParser.className,  LogManager.getExecuteMethodName(), url, e.getMessage());
			e.printStackTrace();
			restore(Parser.REQUEST_FAILED | Parser.LIST_RESTORED,
								Parser.REQUEST_FAILED);
		}catch (SQLException e) {
			LogManager.LogE(Parser.className,  LogManager.getExecuteMethodName(), url, e.getMessage());
			e.printStackTrace();
			this.stateRequest = Parser.DB_INVALID;
			
		}catch (Exception e) {
			LogManager.LogE(Top100ClansParser.className,  LogManager.getExecuteMethodName(),
					e.getLocalizedMessage());
			
			if (WidgetProvider.RESTORE_ACTION.equals(e.getMessage())) {
				restore(Parser.LIST_RESTORED, Parser.REQUEST_FAILED);
			}
			else{
				this.stateRequest = Parser.REQUEST_FAILED;
				e.printStackTrace();
			}
		}
		return this.stateRequest;
	}

	@Override
	protected void restore(int complete, int failed)	throws Exception {
		try {
			int count = AppManager.getDatabase().getRankTable().getCountCurrentUrl();
			
			if(count == -1){
				throw new Exception( LogManager.getExecuteMethodName() + " - DB empty");
			}
		
			this.stateRequest = complete;
			LogManager.LogV(Top100ClansParser.className,  LogManager.getExecuteMethodName());
		}catch (SQLException e) {
			e.printStackTrace();
			throw new SQLException(String.format(
					"%s - error = %s",  LogManager.getExecuteMethodName(), e.getMessage()));
		}catch (Exception e1) {
			e1.printStackTrace();
			this.stateRequest = failed;
	
			throw new Exception(String.format(
					"%a - error = %s",  LogManager.getExecuteMethodName(),e1.getMessage()));
		}
	}
	@Override
	public ArrayList<Top100ClansItem> parseXML(Document doc, int limit) throws Exception {
		try {
			ArrayList<Top100ClansItem> top100ClansList = new ArrayList<Top100ClansItem>();
			
			Elements listPlayers = doc.select("li");

			int index = 0;
			for (Element listElement: listPlayers) {
				top100ClansList.add(this.getItem(listElement));
				index++;

				if(limit >= 0 && index == limit) break;
			}
			
			return top100ClansList;
		} 
		catch (SQLException e) {
			e.printStackTrace();
			throw new SQLException(String.format(
					"%s - doc = %s; error = %s",  LogManager.getExecuteMethodName(), (doc == null) ? doc == null :doc.toString(),
					e.getMessage()));
		}
		catch (Exception e) {
			e.printStackTrace();
			this.stateRequest = Top100ClansParser.XML_INVALID;

			throw new Exception(String.format(
					"%s - doc = %s; error = %s",  LogManager.getExecuteMethodName(), (doc == null) ? doc == null :doc.toString(), e.getMessage()));
		}
	}
	@Override
	protected Top100ClansItem getItem(Element elem) throws Exception{
		Top100ClansItem item = new Top100ClansItem();
		item.setPos(this.parseInt(elem.select("div.position2").first().text()));
		item.setClanName(elem.select("div.clanname").first().text());
		item.setOwnerNickname(elem.select("div.clanname").get(1).text());
		item.setPos2(this.parseInt(elem.select("div.position3").first().text()));
		item.setPos3(this.parseInt(elem.select("div.position4").first().text()));

		return item;
	}

	@Override
	public Object parseXML(JSONObject doc, int limit) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	
}